package com.ruoyi.project.modules.page.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.modules.category.service.ICategoryService;
import com.ruoyi.project.modules.fileInfo.domain.FileInf;
import com.ruoyi.project.modules.fileInfo.service.IFileInfoService;
import com.ruoyi.project.modules.interfaceObject.domain.InterfaceObject;
import com.ruoyi.project.modules.interfaceObject.service.IInterfaceObjectService;
import com.ruoyi.project.modules.interfaceinfo.domain.InterfaceInfo;
import com.ruoyi.project.modules.interfaceinfo.service.IInterfaceInfoService;
import com.ruoyi.project.modules.page.domain.Page;
import com.ruoyi.project.modules.page.domain.PageInterfaceDto;
import com.ruoyi.project.modules.page.service.IPageService;
import com.ruoyi.project.modules.pageTag.service.IPageTagService;
import com.ruoyi.project.modules.table.domain.TableInfo;
import com.ruoyi.project.modules.table.service.ITableInfoService;
import com.ruoyi.project.modules.usage.domain.Usage;
import com.ruoyi.project.modules.usage.service.IUsageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Controller
@RequestMapping("/page/page/new")
@Api(tags = "页面驾驶舱")
public class PageNewController extends BaseController {

    private String prefix = "page/page/new";

    @Autowired
    private IPageService pageService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IFileInfoService fileInfoService;

    @Autowired
    private IInterfaceInfoService interfaceInfoService;

    @Autowired
    private IInterfaceObjectService interfaceObjectService;

    @Resource
    private ITableInfoService tableInfoService;

    @Autowired
    private IUsageService usageService;

    @Autowired
    private IPageTagService pageTagService;

    @GetMapping()
    public String toPageListPage() {
        return prefix + "/page";
    }

    /**
     * 查询页面树列表
     */
    @PostMapping("/list")
    @ResponseBody
    public AjaxResult list(Page page) {
        List<Page> list = pageService.selectPageListV2(page);
        return AjaxResult.success(list);
    }

    /**
     * 根据页面id和图片查询查询图片页面列表
     * @param pageId
     * @return
     */
    @PostMapping("/imgList")
    @ResponseBody
    public AjaxResult imgList(@RequestParam Long pageId, @RequestParam("imgType") String imgType) {
        FileInf fileInf = new FileInf();
        fileInf.setObjectId(pageId);
        fileInf.setImgType(imgType);
        fileInf.setObjectType("2");
        List<FileInf> result = this.fileInfoService.selectFileInfoList(fileInf);
        return AjaxResult.success(result);
    }

    /**
     * 根据页面查询接口列表
     *
     * @param pageId
     * @return
     */
    @PostMapping("/interfaceList")
    @ResponseBody
    public AjaxResult interfaceList(@RequestParam Long pageId, @RequestParam Long pageImageId
            , @RequestParam(required = false) Long interfaceId) {
        List<Long> interfaceIds = null != interfaceId
                ? Collections.singletonList(interfaceId)
                : getInterfaceIds(pageId);
        if (CollectionUtil.isEmpty(interfaceIds)) {
            return AjaxResult.success();
        }
        List<InterfaceInfo> interfaceInfoList = this.interfaceInfoService.selectInterfaceInfoByIds(interfaceIds);
        if (CollectionUtil.isEmpty(interfaceInfoList)) {
            return AjaxResult.success();
        }
        if (pageImageId == null) {
            interfaceInfoList.sort(Comparator.comparing(InterfaceInfo::getShowImgType).reversed());
            return AjaxResult.success(interfaceInfoList);
        }
        interfaceInfoList.forEach(a -> {
            FileInf fileInf = new FileInf();
            fileInf.setObjectId(a.getId());
            fileInf.setObjectType("1");
            fileInf.setIsMaster(null);
            fileInf.setImgType(null);
            fileInf.setParentId(pageImageId);
            List<FileInf> fileInfs = this.fileInfoService.selectFileInfoList(fileInf);
            if (CollectionUtil.isEmpty(fileInfs)) {
                return;
            }
            a.setShowImgType(1);
            List<FileInf> infs = new ArrayList<>();
            for (FileInf inf : fileInfs) {
                if ("Y".equals(inf.getIsMaster())) {
                    a.setShowImgType(2);
                    infs.add(inf);
                }
            }
            if (CollectionUtil.isNotEmpty(infs)) {
                a.setFileList(infs);
            }
        });
        interfaceInfoList.sort(Comparator.comparing(InterfaceInfo::getShowImgType).reversed());
        return AjaxResult.success(interfaceInfoList);
    }

    /**
     * 根据页面ID查询关联表
     *
     * @param pageId
     * @return
     */
    @PostMapping("/tableList")
    @ResponseBody
    public AjaxResult tableList(@RequestParam Long pageId) {
        List<Long> interfaceIds = getInterfaceIds(pageId);
        if (CollectionUtil.isEmpty(interfaceIds)) {
            return AjaxResult.success();
        }
        List<Long> tableIds = this.pageService.tableList(interfaceIds);
        if (CollectionUtil.isEmpty(tableIds)) {
            return AjaxResult.success();
        }
        List<TableInfo> tableInfos = this.tableInfoService.selectTableInfoByTableIdsV2(tableIds);
        return AjaxResult.success(tableInfos);
    }

    /**
     * 根据页面ID查询关联用况
     *
     * @param pageId
     * @return
     */
    @PostMapping("/usageList")
    @ResponseBody
    public AjaxResult usageList(@RequestParam Long pageId) {
        List<Long> interfaceIds = getInterfaceIds(pageId);
        if (CollectionUtil.isEmpty(interfaceIds)) {
            return AjaxResult.success();
        }
        InterfaceObject interfaceObject = new InterfaceObject();
        interfaceObject.setObjectType("3");
        interfaceObject.setBffIds(new HashSet<>(interfaceIds));
        List<InterfaceObject> interfaceObjectList = this.interfaceObjectService.selectInterfaceObjectList(interfaceObject);
        if (CollectionUtil.isEmpty(interfaceObjectList)) {
            return AjaxResult.success();
        }
        Set<Long> usageIds = interfaceObjectList.stream().map(InterfaceObject::getObjectId).collect(Collectors.toSet());
        Usage usage = new Usage();
        usage.setUsageIds(usageIds);
        List<Usage> usageList = this.usageService.selectUsageListV2(usage);
        return AjaxResult.success(usageList);
    }

    private List<Long> getInterfaceIds(Long pageId) {
        InterfaceObject interfaceObject = new InterfaceObject();
        interfaceObject.setObjectType("2");
        interfaceObject.setObjectId(pageId);
        List<InterfaceObject> result = this.interfaceObjectService.selectInterfaceObjectList(interfaceObject);
        if (CollectionUtil.isEmpty(result)) {
            return null;
        }
        return result.stream().map(InterfaceObject::getInterfaceId).collect(Collectors.toList());
    }

    /**
     * 根据页面和接口 查询图片
     * @param pageId
     * @return
     */
    @PostMapping("/pageInterfaceImg")
    @ResponseBody
    public AjaxResult pageInterfaceImg(@RequestParam Long pageId, @RequestParam(required = false) String pageTagIds
            , @RequestParam Long interfaceId) {
        if (interfaceId != 0) {
            return AjaxResult.success(this.fileInfoService.pageInterfaceImg(pageId, interfaceId));
        }
        FileInf fileInf = new FileInf();
        fileInf.setObjectType("2");
        fileInf.setImgType("1");
        fileInf.setObjectId(pageId);
        if (StringUtils.isEmpty(pageTagIds) || "0".equalsIgnoreCase(pageTagIds)) {
            List<FileInf> data = this.fileInfoService.selectFileInfoList2(fileInf);
            if (CollectionUtil.isNotEmpty(data)) {
                for (FileInf datum : data) {
                    if (CollectionUtil.isNotEmpty(datum.getChildren())) {
                        for (FileInf child : datum.getChildren()) {
                            if("Y".equals(child.getIsMaster())) {
                                datum.setRed(true);
                                break;
                            }
                        }
                    }
                }
            }
            return AjaxResult.success(data);
        }
        List<Long> tagIds = Arrays.asList(pageTagIds.split(","))
                .stream().map(a -> Long.parseLong(a))
                .collect(Collectors.toList());
        List<FileInf> list = this.pageTagService.queryFileInfoByPageTagIds(tagIds);
        if (null == list || list.size() == 0) {
            return AjaxResult.success();
        }
        List<Long> fileIds = list.stream().map(FileInf::getId).collect(Collectors.toList());
        fileInf.setIds(fileIds);
        List<FileInf> data = this.fileInfoService.selectFileInfoList2(fileInf);
        if (CollectionUtil.isNotEmpty(data)) {
            for (FileInf datum : data) {
                if (CollectionUtil.isNotEmpty(datum.getChildren())) {
                    for (FileInf child : datum.getChildren()) {
                        if("Y".equals(child.getIsMaster())) {
                            datum.setRed(true);
                            break;
                        }
                    }
                }
            }
        }
        return AjaxResult.success(data);
    }

    /**
     * 根据页面大图id和接口id查询 接口局部图片
     * @return
     */
    @PostMapping("/queryPartImgByParentIdAndInterface")
    @ResponseBody
    public AjaxResult queryPartImgByParentIdAndInterface(@RequestParam Long parentId, @RequestParam Long interfaceId) {
        List<FileInf> fileInfs = this.fileInfoService.queryPartImgByParentIdAndInterface(parentId, interfaceId);
        for (FileInf fileInf : fileInfs) {
            if("Y".equals(fileInf.getIsMaster())) {
                fileInf.setRed(true);
            }
        }
        return AjaxResult.success(fileInfs);
    }

    /**
     * 添加接口页面
     * @param pageId 页面id
     * @param modelMap modelMap
     * @return 页面地址
     */
    @GetMapping("/addInterface")
    public String addInterface(Long pageId, ModelMap modelMap) {
        modelMap.put("pageId", pageId);
        return prefix + "/addInterface";
    }

    /**
     * 添加接口局部图
     * @param interfaceId 接口id
     * @param interfaceImgId 接口图片id
     * @param modelMap modelMap
     * @return 页面地址
     */
    @GetMapping("/addDescription")
    public String addDescription(Long interfaceId, Long interfaceImgId, String isMaster, ModelMap modelMap) {
        modelMap.put("interfaceId", interfaceId);
        modelMap.put("interfaceImgId", interfaceImgId);
        modelMap.put("isMaster", isMaster);
        return prefix + "/addDescription";
    }


    @GetMapping("add_img/{pageId}/{imgType}")
    public String add_bff_img(@PathVariable("pageId") Long pageId,
                              @PathVariable("imgType") String imgType,
                              @RequestParam(value = "imageId",required = false,defaultValue = "0") Long imageId,
                              ModelMap mmap) {
        mmap.put("pageId", pageId);
        mmap.put("imgType", imgType);
        mmap.put("imageId", imageId);
        return prefix + "/add_img";
    }

    @GetMapping("setOrder/{pageId}/{id}")
    public String setOrder(@PathVariable("pageId") Long pageId, @PathVariable("id") Long id, ModelMap mmap) {
        mmap.put("pageId", pageId);
        mmap.put("id", id);
        FileInf fileInf = this.fileInfoService.selectFileInfoById(id);
        mmap.put("fileInf", fileInf);
        return prefix + "/setOrder";
    }

    /**
     * 更新页面标签
     * @param pageId  页面id
     * @param type 类型
     * @param pageImgId 页面局部图id
     * @param mmap
     * @return
     */
    @GetMapping("updatePageTag/{pageId}/{type}")
    public String updatePageTag(@PathVariable("pageId") Long pageId,
                                @PathVariable("type") int type,
                                @RequestParam(value = "pageImgId", required = false) Long pageImgId,
                                ModelMap mmap) {
        mmap.put("pageId", pageId);
        mmap.put("type", type);
        mmap.put("pageImgId", pageImgId);
        return prefix + "/updatePageTag";
    }

    /**
     * 设置页面标签
     * @param pageId 页面id
     * @param mmap
     * @return
     */
    @GetMapping("editPageTag/{pageId}")
    public String editPageTag(@PathVariable("pageId") Long pageId,
                              ModelMap mmap) {
        mmap.put("pageId", pageId);
        return prefix + "/editPageTag";
    }

    @GetMapping("setParamSource/{pageId}/{interfaceId}")
    public String parameterSourceSet(@PathVariable("pageId") Long pageId,
                                     @PathVariable("interfaceId") Long interfaceId,
                                     @RequestParam(value = "pageImgId", required = false) Long pageImgId,
                                    ModelMap mmap) {
        mmap.put("pageId", pageId);
        mmap.put("interfaceId", interfaceId);
        mmap.put("pageImgId", pageImgId);
        InterfaceInfo interfaceInfo = this.interfaceInfoService.selectInterfaceInfoById(interfaceId);
        mmap.put("interfaceInfo", interfaceInfo);
        return prefix + "/setInParamSource";
    }

    /**
     * 设置字段来源
     * @param pageId  页面id
     * @param interfaceFieldId 页面字段id
     * @param interfaceId  接口id
     * @param pageImgId 局部图id
     * @param type 类型
     * @param mmap
     * @return
     */
    @GetMapping("setSource/{pageId}/{interfaceFieldId}")
    public String sourceSet(@PathVariable("pageId") Long pageId,
                            @PathVariable("interfaceFieldId") Long interfaceFieldId,
                            @RequestParam(value = "interfaceId", required = false) Long interfaceId,
                            @RequestParam(value = "pageImgId", required = false) Long pageImgId,
                            @RequestParam(value = "type", required = false) int type,
                            ModelMap mmap) {
        mmap.put("pageId", pageId);
        mmap.put("pageImgId", pageImgId);
        mmap.put("interfaceId", interfaceId);
        mmap.put("interfaceFieldId", interfaceFieldId);
        mmap.put("type", type);
        return prefix + "/setSource";
    }

    /**
     * 设置接口排序
     * @param pageId 页面id
     * @param modelMap modelMap
     * @return 页面地址
     */
    @GetMapping("/setInterfaceOrder")
    public String setInterfaceOrder(Long pageId, ModelMap modelMap) {
        modelMap.put("pageId", pageId);
        return prefix + "/setInterfaceOrder";
    }

    @GetMapping("/queryInterfaceByPageId")
    @ResponseBody
    @ApiOperation("查询页面接口列表")
    public AjaxResult queryInterfaceByPageId(Long pageId) {
        List<InterfaceInfo> list = this.pageService.queryInterfaceByPageId(pageId);
        return AjaxResult.success(list);
    }

    @PostMapping("/updatePageInterfaceSort")
    @ResponseBody
    @ApiOperation("更新页面接口排序")
    public AjaxResult updatePageInterfaceSort(@RequestBody List<PageInterfaceDto> pageInterfaceDtoList) {
        this.pageService.updatePageInterfaceSort(pageInterfaceDtoList);
        return success();
    }
}
